 
import * as echarts from '../../../ec-canvas/echarts';
import { formatNumber, colorRgba, countS} from '../../../utils/util.js';
import { getComacToday } from '../../../api/getData.js'
import colorObj from '../../../utils/colorList.js'
let chart = null;
const systemInfo = wx.getSystemInfoSync();

Component({
  properties: {
    deviceid: {
      type: String
    },
    show: {
      type: String,
    }
  },

  data: {
    renderComplete: false,
    renderOver: false,
    active: '1',
    runtime: {
      type: Object
    },
    daily: {
      type: Object
    },
    weekstate: {
      type: Object
    },
    ec: {
      lazyLoad: true
    },
    nowTime: 0,
    runTime: [],
    history: null,
    username: null,
    moduleID: '',
    todayOee: '',
    stableCondition: '',
    stableHealth: '',
    systemInfo: systemInfo.windowWidth,
    partData: [],
    deviceStateColor: ''
  },
  attached() {
    this.getTime()
  },
  ready() {
    
  },
  pageLifetimes: {
    show(){
    }
  },
  methods: {
    // 改变active
    changeActive (str) {
      if (!this.data.renderOver) {
        const { daily, weekstate } = this.data;
        let data1, data2;
        this.setData({
          active: str.target.dataset.activeid
        })
        wx.setStorageSync('activeCate', str.target.dataset.activeid)
        // let data = str.target.dataset.activeid === '1' ? daily : weekstate
        if (str.target.dataset.activeid === '1') {
          data2 = null;
          let data1 = daily;
          this.selectComponent(".health-cate").countEcharts(data1, str.target.dataset.activeid);
        }
        if (str.target.dataset.activeid === '2') {
          data1 = null;
          let data2 = weekstate;
          this.selectComponent(".health-cate").countEcharts(data2, str.target.dataset.activeid);
        }     
      }
      this.setData({
        renderOver: true
      })
    },
    // health-cate图表加载完执行事件
    onMyEventCate() {
      this.setData({
        renderOver: false
      })
    },
    radioChange (e) {
      const { value } = e.detail;
      this.setData({
        renderComplete: true
      })
      wx.setStorageSync('radioChange', value)
      this.selectComponent(".health-line-compare").getLineOption(value);
    },
    // health-line-compare图表加载完执行事件
    onMyEvent() {
      this.setData({
        renderComplete: false
      })
    },
    // 父级调用的函数
    getSocket (detail){
      let { deviceID } = detail;
      this.sendSocket(deviceID)
    },
    getTime(){
      let data = new Date();
      let Y = data.getFullYear();
      let M = formatNumber(data.getMonth() + 1);
      let D = formatNumber(data.getDate());
      let h = formatNumber(data.getHours());
      let m = formatNumber(data.getMinutes());
      this.setData({
        nowTime: `${Y}-${M}-${D} 00:00-${h}:${m}`,
        username: wx.getStorageSync('username')
      })
    },
    // 调用绘制echarts图方法
    setEcharts(data){
      this.setData({
        moduleID: wx.getStorageSync('moduleList_new')[0] ? wx.getStorageSync('moduleList_new')[0].moduleID : wx.getStorageSync('moduleList')[0] && wx.getStorageSync('moduleList')[0].moduleID,
        active: wx.getStorageSync('activeCate') || '1'
      });
      const { moduleID } = this.data;
      switch (data.cmd) {
        case 'assessment': // 设备信息
          if (this.data.username === "widia") return
          if (moduleID === "health_comac" || moduleID === "health_tobaccoxiamen") {
            this.setData({
              stableHealth: data.result.stableHealth,
              stableCondition: data.result.stableCondition
            })
            this.selectComponent('.health-gauge').initEchartObj()
            this.selectComponent('.health-gauge').countEcharts(data)
          }
          break;
        case 'assessmenta': // 设备信息
          if (this.data.username === "widia") return
          if (moduleID === "health" || moduleID === "health_motor" || moduleID === "healthComacLathe") {
            this.selectComponent('.health-gauge').initEchartObj()
            this.selectComponent('.health-gauge').countEcharts(data)
            if (moduleID === "healthComacLathe"){
              // this.selectComponent('.health-line').initEchartObj()
              this.selectComponent('.health-line').countEcharts(data)
            }
            getComacToday(data.result.deviceID).then(res => {
              if (res.resCode === "SUCCESS") {
                this.setData({
                  partData: res.result
                })
              }
            })
          }     
          break;
        case 'healthcurve': // 实时健康度曲线
          if (this.data.username === "widia") return
          if (moduleID === "health_comac" || moduleID === "health_tobaccoxiamen") {
            wx.setStorageSync('comacHealthcurve', data)
            this.selectComponent('.health-line').countEcharts(data)
            // this.selectComponent('.health-line').initEchartObj()
          }         
          break;
        case 'ahealthcurve': // 实时健康度曲线
          if (this.data.username === "widia") return
          if (moduleID === "health" || moduleID === "health_motor") {
            // this.selectComponent('.health-line').initEchartObj()
            this.selectComponent('.health-line').countEcharts(data)
          }
          break;
        case 'trendcurve': // 健康评估对比
          if (this.data.username === "widia") return
          // 这里加了判断 因为登录pgtj账号在这执行下面方法获取字段不对
          if (moduleID !== "health" && this.data.username !== 'pgtj' && moduleID !== 'healthComacLathe') {
            wx.setStorageSync('comacTrendcurve', data)
            this.selectComponent('.health-line-compare').countEcharts(data)
          }
          break;
        case 'atrendcurve': // 健康评估对比
          if (this.data.username === "widia") return
          if (moduleID === "health" || moduleID === "health_motor") {
            this.selectComponent('.health-line-compare').countEcharts(data)
          }
          break;  
        case 'runtime': // 状态统计
          // 计算运转时间
          if (this.data.username === "widia") return
          let run = data.result.status.filter((item) => item.name === "运转");
          let runTime = ['00', '00', '00'];
          if (run.length){
            let s = run[0].time;
            let h = formatNumber( parseInt(s / 3600) );
            s = s % 3600;
            let m = formatNumber(parseInt(s / 60))
            s = formatNumber(s % 60)
            runTime = [h, m, s]
          }
          let pieChart = this.selectComponent("#mychart-dom-pie")
          this.getTime()
          pieChart.init((canvas, width, height) => {
            const Chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            Chart.setOption(this.getPieOption(data.result))
            return Chart
          })
          
          this.setData({
            runtime: data.result,
            runTime: runTime,
          })
          break;
          // 解决锁屏之日状态统计和周状态统计多次渲染的问题
        case 'daystate':
          if (this.data.username === "widia") return
          this.setData({
            daily: data
          })
          if (this.data.active === '1') {
            if (!this.data.renderOver) {
              this.selectComponent('.health-cate').countEcharts(data)
            }
          }
          break;
        case 'weekstate':
          if (this.data.username === "widia") return
          this.setData({
            weekstate: data
          })
          if (this.data.active === '2') {
            if (!this.data.renderOver) {
              this.selectComponent('.health-cate').countEcharts(data)
            }
          }  
          break;
        case 'history':
          if (this.data.username === "widia") return
          let category = this.selectComponent("#mychart-dom-category");
          category.init((canvas, width, height) => {
            const Chart = echarts.init(canvas, null, {
              width: width,
              height: height
            });
            Chart.setOption(this.getCategoryOption(data))
          })
          this.setData({
            history: data
          })
          break;
        case 'status':
          if (this.data.username !== "widia") return
          let todayOee = data.result.sumIntval !== 0 
              && Math.ceil((data.result.sumRunTime / data.result.sumIntval) * 100)
              ||  0;

          this.selectComponent('.history-echarts').countEcharts(data)
          this.selectComponent('.history-state').countEcharts(data)
          this.setData({
            todayOee
          })
          break;
      }
    },

    // 配置pie
    getPieOption(result){
      let status = result.status
      let legendName = [];
      let colorListArr = [];
      let totalTime = 0;
      status.forEach(item => {
        totalTime += item.time;
      })

      let len = status.length,
        totalPercent = 0
      

      status.forEach((item, index)=> {
        let percent = 0
        if (index === (len-1)){
          if (item.time != '0'){
            percent = 100 - totalPercent
          } else {
            percent = 0
          }
        } else {
          percent = (item.time != '0' && parseInt((item.time / totalTime)*100) || 0)
          totalPercent += percent
        }
        
        percent = percent +'%';
        item.value = item.time
        item.time === 0 && (item.value = 0.1)
        // colorListArr = ['#FF5F5F', '#ffd285','#3AD5AB', '#8de3fa', '#409EFF', '#909399','#67C23A']
        switch (item.name){
          case '停机':
            // item.name = `${percent} ${item.name}状态`
            item.name = `${item.name}`
            // colorListArr.push('#FF5F5F');
            break;
          case '运转':
            // colorListArr.push('#3AD5AB');
            item.name = `${item.name}`
            break;
          case '卸载':
            item.name = `${item.name}`
            // colorListArr.push('#859bf4');
            break;
          case '异常':
            item.name = `${item.name}`
            // colorListArr.push('#ffd285');
            break;
          case '过渡':
            item.name = `${item.name}`
            // colorListArr.push('#cddc39');
            break;
          case '放电':
            item.name = `${item.name}`
            // colorListArr.push('#409EFF');
            break;
          case '清理':
            item.name = `${item.name}`
            // colorListArr.push('#63e0ff');
            break;
          case '放电干扰':
            // colorListArr.push('#909399');
            item.name = `${item.name}`
            break;
          case '待机':
            // colorListArr.push('#ba2f2b');
            item.name = `${item.name}`
            break;
        }
        colorListArr.push(colorObj[item.name]);
        legendName.push(item.name);
      })
      let deviceStateColor = ''
      // switch (result.deviceState) {
      //   case '停机':
      //     // item.name = `${percent} ${item.name}状态`
      //     deviceStateColor = '#FF5F5F'
      //     break;
      //   case '运转':
          
      //     deviceStateColor = '#3AD5AB'
      //     break;
      //   case '卸载':
      //     deviceStateColor = '#859bf4'
          
      //     break;
      //   case '异常':
      //     deviceStateColor = '#ffd285'
          
      //     break;
      //   case '过渡':
      //     deviceStateColor = '#cddc39'
          
      //     break;
      //   case '放电':
      //     deviceStateColor = '#409EFF'
          
      //     break;
      //   case '清理':
      //     deviceStateColor = '#63e0ff'
          
      //     break;
      //   case '放电干扰':
      //     deviceStateColor = '#FF5F5F'
      //     break;
      // }
      deviceStateColor=colorObj[result.deviceState];
      this.setData({
        deviceStateColor
      })
      
      legendName = status.map(item => item.name);
      return {
        animation: false,
        tooltip: {
          show: false
        },
        legend: {
          // orient: 'vertical',
          x: 'center',
          // top: 'middle',
          y: 'top',
          data: legendName,
          itemWidth: 16,
          itemHeight: 10,
          textStyle: {
            color: colorListArr,
            fontSize: 14,
          },
        },
        grid: {
          top: '5%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            name: '状态统计',
            type: 'pie',
            // center: ['50%', '60%'],
            // radius: ['50%', '70%'],
            radius: '70%',
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: status,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              normal: {
                color: function (params) {
                  //自定义颜色
                  var colorList = colorListArr;
                  return colorList[params.dataIndex]
                }
              }
            },
             tooltip: {
              trigger: 'item',
              show: true,
              confine: true,
              extraCssText: "z-index:98",
              formatter: function (params) {
                let result = params.seriesName;
                result += "\n" + params.name + ': ' + (params.value / 3600).toFixed(2) + '小时' + '(' + params.percent + '%)';
                return result;
              }
            }
          },
          {
            name: '状态统计',
            type: 'pie',
            radius: '50%',
            avoidLabelOverlap: false,
            hoverAnimation: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [1],
            z: 10,
            itemStyle: {
              color: '#595c68'
            }
          }
        ]
      };

    },
    // 配置柱状图
    getCategoryOption(result){
      let legend = [],
      colorList = [],
      series = [],
      xAxisData = [];

      for (let key in result.color){
        colorList.push(result.color[key])
        let stack = wx.getStorageSync('moduleConfig').health_tobaccoxiamen.stack;
        legend.push(key);
        series.push({
            name: key,
            type: 'bar',
            stack: stack,
            barWidth: '7.5',
            label: {
              normal: {
                position: 'insideRight'
              }
            },
            itemStyle: {
              color: colorList[colorList.length - 1]
            },
          data: countS(result.runtime[key], 60)
        })
      }
      result.labels.forEach(item => {
        let _D = item.split(' ')[1].split(':');
        _D.pop()
        xAxisData.push(_D.join(':'))
      })
      
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: legend,
          itemWidth: 10.5,
          itemHeight: 7.5,
          textStyle: {
            color: colorList,
            fontSize: 9,
          }
        },
        grid: {
          top: 24,
          left: 24,
          right: 30,
          bottom: 26,
          height: systemInfo.screenWidth <= 360 && 100 || 120
        },
        xAxis: {
          name: '时间',
          animation: false,
          nameGap: 5.5,
          type: 'category',
          
          data: xAxisData,
          splitLine: {
            show: false
          },

          nameTextStyle: {
            color: "#BAD7FF",
            fontSize: 12,

          },
          axisLabel: {
            margin: 10,
            color: "#BAD7FF",
            fontSize: 9,
            // interval: 1
          },
          axisLine: {
            lineStyle: {
              color: {
                type: 'linear',
                colorStops: [{
                  offset: 0, color: '#39529A'
                }, {
                  offset: 1, color: '#39529A' // 100% 处的颜色
                }],
              }
            }
          },
        },
        yAxis: {
          type: 'value',
          name: '分钟',
          nameGap: 5.5,
          min: 0,
          max: 60,
          splitLine: {
            show: false
          },
          nameTextStyle: {
            color: "#BAD7FF",
            fontSize: 12,
          },
          axisLabel: {
            margin: 10,
            color: "#BAD7FF",
            fontSize: 9
          },
          axisLine: {
            lineStyle: {
              color: {
                type: 'linear',
                colorStops: [{
                  offset: 0, color: '#39529A'
                }, {
                  offset: 1, color: '#39529A' // 100% 处的颜色
                }],
              }
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#6B6E7B'
            }
          }
        },
        series: series
      }
    }
  }
})